package com.example.liwushuo.fragment;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.example.liwushuo.BaseApp;
import com.example.liwushuo.R;
import com.example.liwushuo.adapter.SearchGifAdapter;
import com.example.liwushuo.bean.search.BaseSearch;
import com.example.liwushuo.bean.search.Search;
import com.example.liwushuo.urls.urls;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class SearchGifFragment extends Fragment implements OnItemClickListener {

	private String key;
	private String url;
	private GridView gridView;
	private List<Search> list;
	private SearchGifAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		key = getArguments().getString("key");
		url = urls.getSearchUrl(key);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.search, null);
		gridView = (GridView) view.findViewById(R.id.search_gridView_id);
		initView();
		initData();
		return view;
	}

	private void initView() {

		list = new ArrayList<Search>();
		adapter = new SearchGifAdapter(getActivity(), list);
		gridView.setAdapter(adapter);

	}

	private void initData() {

		BaseApp.getHttpUtils().send(HttpMethod.GET, url,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {

					}

					@Override
					public void onSuccess(ResponseInfo<String> response) {

						String json = response.result;
						BaseSearch baseSearch = JSONObject.parseObject(json,
								BaseSearch.class);

						if (baseSearch != null
								&& "OK".equals(baseSearch.getMessage())) {

							list.addAll(baseSearch.getData().getItems());
							adapter.notifyDataSetChanged();

						}

					}
				});

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		Long id2 = list.get(position).getId();
		Log.i("id2","------------>>>>>>>>"+id2);

	}

}
